# Create your views here.

from django.shortcuts import render
from django.db.models import Avg
from .models import JdQipaoshui


def jd_qipaoshui_show(request):
    shorts = JdQipaoshui.objects.all()
    counter = JdQipaoshui.objects.all().count()

    # 平均星级
    star_avg = f"{JdQipaoshui.objects.aggregate(Avg('comment_star'))['comment_star__avg']:0.1f}"
    # 情感倾向
    sent_avg = f"{JdQipaoshui.objects.aggregate(Avg('sentiments'))['sentiments__avg']:0.2f}"

    # 正向数量
    queryset = JdQipaoshui.objects.values('sentiments')
    condtions = {'sentiments__gte': 0.5}
    plus = queryset.filter(**condtions).count()

    # 负向数量
    queryset = JdQipaoshui.objects.values('sentiments')
    condtions = {'sentiments__lt': 0.5}
    minus = queryset.filter(**condtions).count()

    return render(request, 'result1.html', locals())


def search(request):
    key_word = request.GET.get('keywords')
    queryset = JdQipaoshui.objects.all()
    conditions = {}
    if request.GET.get('date_end'):
        date_end = request.GET.get('date_end')
        conditions['comment_tm__lte'] = date_end
    if request.GET.get('date_start'):
        date_start = request.GET.get('date_start')
        conditions['comment_tm__gte'] = date_start
    if key_word:
        conditions['comment__icontains'] = key_word
    shorts = queryset.filter(**conditions)
    counter = shorts.count()
    # 情感倾向
    if counter:
        sent_avg = f" {shorts.aggregate(Avg('sentiments'))['sentiments__avg']:0.2f} "
        star_avg = f"{shorts.aggregate(Avg('comment_star'))['comment_star__avg']:0.1f}"

        # 正向数量
        queryset = shorts.values('sentiments')
        condtions = {'sentiments__gte': 0.5}
        plus = queryset.filter(**condtions).count()

        # 负向数量
        queryset = shorts.values('sentiments')
        condtions = {'sentiments__lt': 0.5}
        minus = queryset.filter(**condtions).count()
    else:
        sent_avg, plus, minus, star_avg = 0, 0, 0, 0
    return render(request, 'result1.html', locals())
